<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">
    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅要素名可查）"
                style="width: 20%"
                clearable></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="addElement">新增要素</el-button>
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="elementId" width="100" label="要素ID"/>
      <el-table-column sortable prop="element" width="250" label="要素"/>
      <el-table-column sortable prop="username" width="220" label="创建者"/>
      <el-table-column sortable prop="createTime" width="250" label="创建时间"/>


      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.elementId)">
            <template #reference>
              <el-button link type="primary" :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>


    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 15, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>

  <!--编辑要素-->
  <el-dialog style="margin-top: 200px" v-model="data.centerDialogVisible" title="更新要素名" width="30%" center>
    <el-form :model="data.form" label-width="60px" ref="userTableFormRef">
      <el-form-item style="margin-left: 50px" label="要素名">
        <el-input v-model="data.form.element" style="width: 80%;" placeholder="请更新要素"/>
      </el-form-item>
    </el-form>

    <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveEdit">确认</el-button>
            </span>
    </template>
  </el-dialog>

  <!--新增要素-->
  <el-dialog style="margin-top: 200px" v-model="data.DialogVisible" title="添加要素" width="30%" center>
    <el-tabs v-model="data.activeTabName" type="border-card">
      <el-tab-pane name="manual" label="手动添加">
        <el-form :model="data.addForm" label-width="60px" ref="userTableFormRef">
          <el-form-item style="margin-left: 50px" label="要素名">
            <el-input v-model="data.addForm.element" style="width: 80%;" placeholder="请输入添加的要素名"/>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane name="upload" label="从本地上传文件" style="display: flex;justify-content: center">
        <el-upload
            multiple
            :action="uploadAction"
            :show-file-list="false"
        >
          <el-button type="primary">点击上传文件</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane name="select" label="从我的文件选择">
        <div class="infinite-list-wrapper" style="overflow: auto;width: 100%;height: 200px;">
          <ul
              v-infinite-scroll="load"
              class="list"
              :infinite-scroll-disabled="disabled"
          >
            <li style="cursor: pointer"
                v-for="i in data.myFileData"
                :key="i"
                v-show="i.fileType === 'pdf'"
                :class="{ selected: data.selectedFile === i.fileName }"
                @click="selectFile(i.fileName,i.fileId)"
                class="list-item">
              {{ i.fileName }}
            </li>
          </ul>
          <p v-if="loading">加载中...</p>
          <p v-if="noMore">没有更多了</p>
        </div>
      </el-tab-pane>
    </el-tabs>


    <template #footer>
      <el-button @click="data.DialogVisible = false">取消</el-button>
      <el-button v-if="data.activeTabName === 'manual'"
                 type="primary"
                 @click="save">
        确认
      </el-button>
      <!-- 显示“选择该文件”按钮仅在从我的文件选择标签页 -->
      <el-button v-if="data.activeTabName === 'select'"
                 type="primary"
                 @click="selectFileActionSave">
        选择该文件
      </el-button>
    </template>
  </el-dialog>


  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {computed, reactive, ref} from "vue";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request.js";
import {Delete, Edit} from '@element-plus/icons-vue'
import {PYTHON_API_BASE_URL} from "@/config.js";

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userData = dataString ? JSON.parse(dataString) : null;

const route = useRoute();

const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  //新增要素弹窗
  DialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  myFileData: [],
  selectedRows: [],//批量删除的数组
  specId: route.query.specId,//点击查看规范的specId
  form: {},//更新要素的表单
  addForm: {
    element: "",
  },//添加要素的表单
  dataLength: '',
  selectedFile: '',
  selectedFileId: null,
  activeTabName: 'manual',//标签切换
})

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/specification/detail?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}&specId=${data.specId}`)
      .then((response) => {
        console.log("数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close(); // 无论请求成功或失败，都关闭加载动画
      });
};

Load()


//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};


const uploadAction = computed(() => {
  return PYTHON_API_BASE_URL + `/UploadFileToAddElement`;
});

//批量逻辑删除
const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.elementId);
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);
  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定删除选中的文件吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      // const res = await request.delete('/java/specification/element/deleteSpecificationElements/' + selectedIds + '/' + data.specId);
      const res = await request.delete('/java/element/delete/' + selectedIds);
      if (res.code === 200){
        ElMessage.info(res.data)
      }else {
        ElMessage.error(res.data)
      }
      Load();
    } catch (error) {
      Load();
    }
  }
};


const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  data.centerDialogVisible = true;
}


const handleDelete = async (elementId) => {
  const selectedIds = []
  selectedIds.push(elementId)
  try {
    const res = await request.delete('/java/element/delete/' + selectedIds);
    if (res.code === 200){
      ElMessage.info(res.data)
    }else {
      ElMessage.error(res.data)
    }
    Load();
  } catch (error) {
    Load();
  }
}


const save = async () => {
  //1、添加到要素表
  let elementId = Date.now(); // 获取当前时间戳作为elementId
  let add = await request.post(`/java/element/addElement?elementId=${elementId}&element=${data.addForm.element}&userId=${userData.userId}`);

  //2、添加到规范要素表
  if (add.code === 200){
    const addData = {
      elementId:elementId,
      specId:data.specId,
    }
    let addSpec = await request.post(`/java/specification/element/pushData`,addData);
    if (addSpec.code === 200){
      ElMessage.info(addSpec.data)
    }else {
      ElMessage.error(addSpec.data)
    }
  }

  data.DialogVisible = false
  Load()
}

const saveEdit = () => {
  request.put(`/java/element/editElement?elementId=`+data.form.elementId + '&element=' + data.form.element).then((res)=>{
    if (res.code === 200){
      ElMessage.info(res.data)
    }else {
      ElMessage.error(res.data)
    }
    data.centerDialogVisible = false
    Load()
  })
}

const selectFileActionSave = () => {
  data.centerDialogVisible = false
}

const addElement = () => {
  data.DialogVisible = true
  loadMyFile();
}


const loadMyFile = () => {
  request.get(`/java/file/findFileByUserId?UserId=${userData.userId}`)
      .then((response) => {
        console.log("数据：", response);
        data.myFileData = response.data
        data.dataLength = response.data.length
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
      });
}


const count = ref(0)
const loading = ref(false)
const noMore = computed(() => count.value >= data.dataLength)
const disabled = computed(() => loading.value || noMore.value)

//滚动的时候触发
const load = () => {
  loading.value = true
  setTimeout(() => {
    count.value += 1
    loading.value = false
  }, 100)
}


const selectFile = (fileName, fileId) => {
  ElMessage.info(fileId + ":" + fileName) // 打印文件名
  data.selectedFile = fileName // 记录选中的文件名
  data.selectedFileId = fileId
  // 其他处理，如果有的话
}

</script>

<style scoped>
.infinite-list-wrapper {
  height: 300px;
  text-align: center;
}

.infinite-list-wrapper .list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list-wrapper .list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-danger-light-9);
  color: var(--el-color-danger);
}

.infinite-list-wrapper .list-item + .list-item {
  margin-top: 10px;
}

.list-item.selected {
  background-color: #409eff; /* 选中项的背景色 */
  color: white; /* 选中项的文字色 */
}
</style>